package demo.practice.leetcode_trie;

import java.util.HashMap;
import java.util.Map;

public class MapSum {
    //P677

    int val=0;
    Map<Character,MapSum> children= new HashMap<>();

    /** Initialize your data structure here. */
    public MapSum() {

    }

    public void insert(String key, int val) {
        MapSum current= this;
        for(int i=0;i<key.length();i++){
            char c = key.charAt(i);
            if(current.children.get(c)==null){
                current.children.put(c,new MapSum());
            }
            current=current.children.get(c);
        }
        current.val=val;
    }

    public int sum(String prefix) {
        MapSum current=this;
        for(int i=0;i<prefix.length();i++){
            char c = prefix.charAt(i);
            if(current.children.get(c)==null){
                return 0;
            }
            current=current.children.get(c);
        }

        return current.val+sum(current);
    }

    public int sum(MapSum current){
        int sum=0;
        for(MapSum child :current.children.values()){
            sum= sum+child.val+sum(child);
        }
        return sum;
    }



}
